package practiceProjects.extractTitlesFromHtmlElement;

/**
 * 从html元素中根据正则表达式提取出标题，豆包提供的代码
 * 从终端输入
 * 理论上是可以在终端用管道符进行输入的，如：
 * type sourceHtmlElement.txt | java TitleExtractor
 * 但powershell的gbk编码格式会使程序无法正常运行
 * 因此用bat更好，直接将txt文件拖到bat文件中
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TitleExtractor {
    private static final Pattern TITLE_PATTERN = Pattern.compile(
            "<div\\s+title\\s*=\\s*[\"']([^\"']+)[\"']", // 支持单/双引号
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL
    );

    public static void main(String[] args) {
        String htmlContent;

        // 优先读取命令行参数文件
        if (args.length > 0) {
            htmlContent = readFromFile(args[0]);
        } else {
            // 否则从终端交互式输入
            System.out.println("请输入HTML内容（按Ctrl+D结束输入）:");
            htmlContent = readFromTerminal();
        }

        if (htmlContent == null) return;

        Matcher matcher = TITLE_PATTERN.matcher(htmlContent);
        int count = 0;

        while (matcher.find()) {
            String title = matcher.group(1);
            System.out.printf("第%d个标题: %s%n", ++count, title);
        }

        if (count == 0) {
            System.out.println("未找到任何<div>标签的title属性");
        }
    }

    private static String readFromFile(String filePath) {
        try {
            return new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            System.err.println("文件读取失败: " + e.getMessage());
            return null;
        }
    }

    private static String readFromTerminal() {
        StringBuilder input = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in))) {

            String line;
            while ((line = reader.readLine()) != null) {
                input.append(line).append(System.lineSeparator());
            }
            return input.toString();
        } catch (IOException e) {
            System.err.println("输入中断: " + e.getMessage());
            return null;
        }
    }
}